package com.seagull.core.test.io.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * @author:jian.zhou
 * @DATE: 2018/1/3.
 * @Version:0.0.1
 * @Desc:
 */
public class AioServer {


    public AioServer ( int port ) throws Exception{

        final AsynchronousServerSocketChannel listen = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
        listen.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel result, Void attachment) {
                listen.accept(null,this);//接受下一个链接
                handle(result);
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("异步io失败");
            }
        });

    }



    public void handle( AsynchronousSocketChannel channel ){
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        channel.read(byteBuffer);
        byteBuffer.flip();

        System.out.println( "asdfasdfa" + new String(byteBuffer.array()));

    }

    public static void main(String[] args) {
        try {
            AioServer aioServer = new AioServer(7080);
            Thread.sleep(100000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
